<!--
 * @Descripttion: 
 * @Author: Kevin
 * @Date: 2022-06-13 17:02:25
 * @LastEditors: Tommy Chen
 * @LastEditTime: 2024-07-11
-->
<template>
  <div>
    <LayoutPanel class="private-common-wrapper">
      <div slot="title" class="title">
        <span>{{ $t('localAccount.authPolicy') }}</span>
      </div>
      <rj-table
        :columns="userGroupColumns"
        :dataSource="authPolicys"
        :pagination="pagination"
        :loading="isTableLoading"
        rowKey="uuid"
        filtercolumns
        @refeshTable="getAuthPolicyList"
        @change="handleTableChange"
      >
        <div slot="customBlock" class="log-opt-wrapper">
          <a-space :size="16">
            <a-button class="icon-btn" type="primary" @click="onAdd">
              <icon-font type="ic-plus" />
              {{ $t('localAccount.addAuthPlicy') }}
            </a-button>
          </a-space>
        </div>
        <!-- qos -->
        <template slot="qos" slot-scope="text, record">
          <a-space :size="12">
            <a-space :size="2">
              <icon-font class="down-arrow" type="ic-decline"></icon-font>
              {{ formatSpeed(record.downloadRateLimit) }}
            </a-space>
            <a-space :size="2">
              <icon-font class="up-arrow" type="ic-rise"></icon-font>
              {{ formatSpeed(record.uploadRateLimit) }}
            </a-space>
          </a-space>
        </template>
        <!-- vlan -->
        <template slot="vlan" slot-scope="text">
          <template v-if="text"> {{ text }} </template>
          <template v-else> -- </template>
        </template>
        <!-- timePeriod -->
        <template slot="timePeriod" slot-scope="text">
          {{ getTimePeriodTxt(text) }}
        </template>
        <!-- quota -->
        <template slot="quota" slot-scope="text">
          {{ getQuotaTxt(text) }}
        </template>
        <!-- acl -->
        <template slot="acl"> -- </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <rj-space :size="16">
            <icon-font type="ic-edit" @click="onEdit(record)" />
            <icon-font type="ic-delete" @click="onDelete(record)" />
          </rj-space>
        </template>
      </rj-table>
      <AddModal ref="addModalRef" @refreshList="getAuthPolicyList" />
    </LayoutPanel>
  </div>
</template>

<script>
import AddModal from './AddModal.vue';
import { requestHttp, maccApi } from '@utils/index';
import { mapState } from 'vuex';
import LayoutPanel from '@views/common/deviceDetail/components/components/layoutPanel.vue';
import { RjTable } from '@components';
import authSysMixin from '@project/authSys/mixin/authSysMixin';
import {
  downloadSpeedOptions,
  uploadSpeedOptions,
  periodOptions,
  dataQuotaOptions,
} from './options';
import { userGroupColumns } from './columns.js';
export default {
  name: 'authPolicy',
  mixins: [authSysMixin],
  components: {
    AddModal,
    'rj-table': RjTable,
    LayoutPanel,
  },
  data() {
    return {
      userGroupColumns,
      pagination: {
        pageSizeOptions: ['10', '20', '50'],
        total: 0,
        current: 1,
        pageSize: 10,
      },
      authPolicys: [],
      isTableLoading: false,
    };
  },
  created() {
    this.getAuthPolicyList();
  },
  computed: {
    ...mapState('User', ['tenantInfo', 'userInfo']),
  },
  methods: {
    handleTableChange(pagination, filterObj) {
      this.pagination = pagination;
      this.getAuthPolicyList();
    },
    formatSpeed(val) {
      if (val == 0) {
        return this.$t('userManage.unlimited');
      } else if (val < 1024) {
        return `${val.toLocaleString('en-US')} Kbps`;
      } else {
        let remainder = val % 1024;
        return remainder
          ? `${val.toLocaleString('en-US')} Kbps`
          : `${(val / 1024).toLocaleString('en-US')} Mbps`;
      }
    },
    formatQuota(val) {
      if (val < 1024) {
        return `${val}MB`;
      } else {
        let remainder = val % 1024;
        return remainder ? `${val}MB` : `${val / 1024} GB`;
      }
    },
    onAdd() {
      this.$refs.addModalRef.openModal();
    },
    onEdit(row) {
      let data = { ...row };
      data.bindMac = Boolean(data.bindMac);
      let ele = this.$refs.addModalRef;
      // 遍历是否有非选项内的值
      let currUploadSpeed = uploadSpeedOptions.find(
        (item) => item.value == data.uploadRateLimit
      );
      let currDownloadSpeed = downloadSpeedOptions.find(
        (item) => item.value == data.downloadRateLimit
      );
      let currTimePeriod = periodOptions.find(
        (item) => item.value == data.timePeriod
      );
      let currDataQuota = dataQuotaOptions.find(
        (item) => item.value == data.quota
      );
      if (data.noOfDevice > 9) {
        data.noOfDevice = 'customDeviceNo';
        ele.customDeviceNo = row.noOfDevice;
      }
      // 处理自定义上传速度
      if (!currUploadSpeed) {
        data.uploadRateLimit = 'userdefinedUpload';
        let flag = this.formatSpeed(row.uploadRateLimit).includes('Kbps');
        ele.customUploadRateLimit.unit = flag ? 'Kbps' : 'Mbps';
        ele.customUploadRateLimit.value = flag
          ? row.uploadRateLimit
          : row.uploadRateLimit / 1024;
      }
      // 处理自定义下载速度
      if (!currDownloadSpeed) {
        data.downloadRateLimit = 'userdefinedDownload';
        let flag = this.formatSpeed(row.downloadRateLimit).includes('Kbps');
        ele.customDownloadRateLimit.value = row.downloadRateLimit;
        ele.customDownloadRateLimit.unit = flag ? 'Kbps' : 'Mbps';
        ele.customDownloadRateLimit.value = flag
          ? row.downloadRateLimit
          : row.downloadRateLimit / 1024;
      }
      // 处理自定义数据用量
      if (!currDataQuota) {
        data.quota = 'userdefined';
        let flag = this.formatQuota(row.quota).includes('MB');
        ele.customQuota.value = row.quota;
        ele.customQuota.unit = flag ? 'MB' : 'GB';
        ele.customQuota.value = flag ? row.quota : row.quota / 1024;
      }
      // 处理自定义时间
      if (!currTimePeriod) {
        data.timePeriod = 'userdefinedperiod';
        const unitTimes = [
          {
            unit: 'weeks',
            time: 60 * 24 * 7,
          },
          {
            unit: 'days',
            time: 60 * 24,
          },
          {
            unit: 'hours',
            time: 60,
          },
        ];
        let { timePeriod } = row;
        let num;
        let unitTime = unitTimes.find((item) => {
          let remainder = timePeriod % item.time;
          if (!remainder) {
            num = timePeriod / item.time;
            return !remainder;
          }
        });
        if (unitTime) {
          ele.customTimePeriod.unit = unitTime.unit;
          ele.customTimePeriod.value = num;
        } else {
          ele.customTimePeriod.value = timePeriod;
        }
      }
      data.originGroupName = data.userGroupName;
      data.isBindSsid = !!data.isBindSsid;
      if (data.isBindSsid) {
        let ssidOpts = this.$refs.addModalRef.ssidOpts;
        let curr = ssidOpts.find((item) => item.value == data.bindSsid);
        if (!curr) {
          data.ssidName = data.bindSsid;
        }
        data.bindSsid = curr ? data.bindSsid : 'custom';
      }
      this.$refs.addModalRef.openModal(data);
    },
    async getAuthPolicyList() {
      this.isTableLoading = true;
      const res = await this.requestHttpAuth({
        api: maccApi.MACC_PROFILE_GET_API,
        method: 'GET',
        replaces: {
          tenantName: this.tenantInfo.tenantName,
          groupId: this.groupId,
        },
        querys: {
          tenantId: this.tenantInfo.tenantId,
          start: (this.pagination.current - 1) * this.pagination.pageSize,
          pageSize: this.pagination.pageSize,
        },
      });
      this.isTableLoading = false;
      if (res.data.code === 0) {
        this.authPolicys = res.data.list;
        this.pagination.total = res.data.count;
      } else {
        this.$message.warning(res.data.msg);
      }
    },
    onDelete(row) {
      this.$confirm({
        title: this.$t('userManage.message'),
        content: this.$t('userManage.deleteRecord'),
        onOk: async () => {
          let replaces = {
            profileUuid: row.uuid,
          };
          const res = await this.requestHttpAuth({
            api: maccApi.MACC_PROFILE_DEL_API,
            method: 'DELETE',
            replaces,
          });

          if (!res.data.code) {
            this.$message.success(this.$t('common.delSuccess'));
            this.getAuthPolicyList();
          } else {
            this.$message.warning(res.data.msg);
          }
        },
      });
    },
    getTimePeriodTxt(timePeriod) {
      const unitTimes = [
        {
          unit: 'weeks',
          time: 60 * 24 * 7,
        },
        {
          unit: 'days',
          time: 60 * 24,
        },
        {
          unit: 'hours',
          time: 60,
        },
      ];
      if (!timePeriod) {
        return this.$t('userManage.unlimited');
      }

      let num;
      let unitTime = unitTimes.find((item) => {
        let remainder = timePeriod % item.time;
        if (!remainder) {
          num = timePeriod / item.time;
          return !remainder;
        }
      });
      const customTimePeriod = {};
      if (unitTime) {
        customTimePeriod.value = num;
        customTimePeriod.unit = unitTime.unit;
      } else {
        customTimePeriod.value = timePeriod;
        customTimePeriod.unit = this.$t('common.minute');
      }
      return `${customTimePeriod.value} ${customTimePeriod.unit}`;
    },
    getQuotaTxt(quota) {
      if (!quota) {
        return this.$t('userManage.unlimited');
      }
      let flag = this.formatQuota(quota).includes('MB');
      const customQuota = {};
      customQuota.unit = flag ? 'MB' : 'GB';
      customQuota.value = flag ? quota : quota / 1024;
      return `${customQuota.value} ${customQuota.unit}`;
    },
  },
};
</script>

<style lang="less" scoped>
.private-common-wrapper {
  padding: 16px;
  overflow: auto;
  height: 100%;
  .title {
    display: flex;
    justify-content: space-between;
  }
}
.log-opt-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
}
.down-arrow {
  color: @success-color;
}
.up-arrow {
  color: @theme-color;
}
</style>
